package com.shaun.tea.controller;

import com.shaun.tea.entity.LoginOfUser;
import com.shaun.tea.entity.User;
import com.shaun.tea.service.UserService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import javax.servlet.http.HttpSession;


@Controller
public class UserController {

    @Autowired
    private UserService userService;


    @RequestMapping("/")
    public String index(Model model) {
        return "index";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public ModelAndView login(Model model, LoginOfUser user, HttpSession httpSession) {
        System.out.println(user);
        User findUser = userService.getOne(
                new QueryWrapper<User>()
                        .eq("user_name", user.getUserName())
                        .eq("password", user.getPassword())
                        .eq("type", user.getType()));
        if (findUser != null) {
            if (findUser.getType() == 0) {
                httpSession.setAttribute("adminName", findUser.getUserName());
                return new ModelAndView(new RedirectView("product/manageProduct"));
            } if (findUser.getType() == 1){
                httpSession.setAttribute("sellerName", findUser.getUserName());
                return new ModelAndView(new RedirectView("product/sellerProduct"));
            }else {
                httpSession.setAttribute("userName", findUser.getUserName());
                return new ModelAndView(new RedirectView("product/toWelcome"));
            }
        }
        return new ModelAndView(new RedirectView("/"));
    }

    @RequestMapping("logout")
    public ModelAndView logout(HttpSession httpSession) {
        httpSession.removeAttribute("adminName");
        httpSession.removeAttribute("userName");
        httpSession.removeAttribute("sellerName");
        return new ModelAndView(new RedirectView("/"));
    }

}
